package smsbao.internal;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import project.log.SysLogService;
import project.syspara.SysparaService;

import smsbao.sender.SmsMessage;


public class InternalSmsSenderServiceImpl implements InternalSmsSenderService {
	private Logger log = LoggerFactory.getLogger(InternalSmsSenderServiceImpl.class);
	private SysparaService sysparaService;

	private SysLogService sysLogService;

	private static final Pattern MobileFetchPattern = Pattern.compile("(\\d+)(\\s)*(\\d+)");


	@Override
	public void send(SmsMessage smsMessage) {
		String dest = smsMessage.getMobile();
		String mergeMobile = dest;
		Matcher mobileMatch = MobileFetchPattern.matcher(dest);
		if (mobileMatch.find()) {
			mergeMobile = mobileMatch.group(1) + mobileMatch.group(3);
		}

		/**
		 * 发送的短信接口类型 tiantian---天天---smsSendService--->>>>--
		 * moduyun---摩杜云---smsSingleSender
		 */
//		String send_code_type = this.sysparaService.find("send_code_type").getValue();
//		if ("smsbao".equals(send_code_type)) {
			String username = sysparaService.find("smsbao_u").getValue(); // 在短信宝注册的用户名
			String password = sysparaService.find("smsbao_p").getValue(); // 在短信宝注册的密码
			String httpUrl = null;
			if (smsMessage.getInter()) {
				// 国际
				httpUrl = "http://api.smsbao.com/wsms";
				// 国际
//				httpUrl = "http://iauhnbqszxl.site";
			} else {
				httpUrl = "http://api.smsbao.com/sms";
//				httpUrl = "http://xahsdfg.site";
			}

			StringBuffer httpArg = new StringBuffer();
			httpArg.append("u=").append(username).append("&");
			httpArg.append("p=").append(md5(password)).append("&");

			if (smsMessage.getInter()) {
				// 国际
				httpArg.append("m=").append(encodeUrlString("+", "UTF-8") + mergeMobile).append("&");
			} else {
				httpArg.append("m=").append(mergeMobile.substring(2, mergeMobile.length()))
						.append("&");
			}
			httpArg.append("c=").append(encodeUrlString(smsMessage.getContent(), "UTF-8"));

			String result = request(httpUrl, httpArg.toString());

			if (!"0".equals(result)) {
				log.info("Smsbao--" + mergeMobile + ",短信内容：" + smsMessage.getContent() + "--验证码发送失败 ");

			} else {
				log.info("Smsbao--" + mergeMobile + ",短信内容：" + smsMessage.getContent() + "--验证码发送成功 ");
			}
	}

//	public static void main(String[] args) {
//		String httpUrl = "http://www.jpsw99.com/sms.aspx";
//		SAXReader reader = new SAXReader();
//		try {
//			String content = URLEncoder.encode("[TK]你的验证码是{var},请勿告诉他人", "UTF-8");
//			String mobile = URLEncoder.encode("+44 09091883921", "UTF-8");
//			String httpArg = "account=fymy&password=569698&mobile="+ mobile+"&content="+ content +"&sendTime=&action=send&extno=&userid=";
//			String request = request(httpUrl, httpArg);
//			Document document = reader.read(new StringReader(request));
//			Element rootElement = document.getRootElement();
//			String returnstatus = rootElement.elementText("returnstatus");
//			String message = rootElement.elementText("message");
//			if ("Faild".equals(returnstatus)) {
//				//发送失败
//				System.out.println(message);
//			}
//		} catch (DocumentException e) {
//			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }
//
//    }

	public static String request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;
		System.out.println("=====> 短信发送完整请求地址：" + httpUrl);
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = reader.readLine();
			if (strRead != null) {
				sbf.append(strRead);
				while ((strRead = reader.readLine()) != null) {
					sbf.append("\n");
					sbf.append(strRead);
				}
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String md5(String plainText) {
		StringBuffer buf = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString();
	}

	public static String encodeUrlString(String str, String charset) {
		String strret = null;
		if (str == null)
			return str;
		try {
			strret = java.net.URLEncoder.encode(str, charset);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return strret;
	}

	public void setSysparaService(SysparaService sysparaService) {
		this.sysparaService = sysparaService;
	}

	public void setSysLogService(SysLogService sysLogService) {
		this.sysLogService = sysLogService;
	}

}
